package SGLisp

import (
	"fmt"
	"strings"

	. "git.oschina.net/yangdao/SGLisp/parse"
	. "git.oschina.net/yangdao/extlib"
	. "git.oschina.net/yangdao/extlib/data_type"
)

func EvalValueFormFile(path string, ctx *Context) interface{} {
	if ctx == nil {
		ctx = MainContext
	}
	tree := LoadAstTree(path)
	node := tree.Roots[0]
	evalList := Evaluate(node, ctx)
	return EvalNode(evalList, ctx)
}

func EvalFormString(str string, ctx *Context) Node {
	tree, err := Reader(strings.NewReader(str), "string", false)
	if err != nil {
		fmt.Println(err)
	}
	return Evaluate(tree.Roots[0], ctx)
}

func EvalValueFormString(str string, ctx *Context) interface{} {
	retNode := EvalFormString(str, ctx)
	return EvalNode(retNode, ctx)
}

func NodeFromExtCollection(srcData interface{}) Node {
	switch srcData.(type) {
	case *TypVector:
		newVecNode := &VectorNode{}
		ForEach(srcData, func(v interface{}) {
			newVecNode.Nodes = append(newVecNode.Nodes, NodeFromExtCollection(v))
		})
		return newVecNode
	case *TypList:
		quoteNode := &QuoteNode{}
		lstNode := &ListNode{}
		ForEach(srcData, func(v interface{}) {
			lstNode.Nodes = append(lstNode.Nodes, NodeFromExtCollection(v))
		})
		quoteNode.Node = lstNode
		return quoteNode
	case *TypMap:
		newMapNode := &MapNode{Val: make(map[interface{}]interface{})}
		ForEach(srcData, func(mapVal interface{}) {
			newMapNode.Val[NodeFromExtCollection(mapVal.(IIndexed).Nth(0)).HashCode()] = NodeFromExtCollection(mapVal.(IIndexed).Nth(1))
		})
		return newMapNode
	case float64, int:
		return &NumberNode{Val: srcData}
	case string:
		return &StringNode{Val: srcData.(string)}
	}
	return nil
}
